<?php
$dbh = new PDO('mysql:host=localhost;dbname=blog' ,
                'root' , '' );
// Check if a blog title already exists
function blogExists($dbh, $blogTitle) {
    $sql = "SELECT COUNT(*) AS cnt FROM blogList
             WHERE blogTitle=".$dbh->quote($blogTitle);
    $row = $dbh->query($sql)->fetch();
    return !empty($row['cnt' ]);
}
// Insert a new blog into the list
function insertBlog($dbh, $blogTitle, $blogText) {
    $sql = "INSERT INTO blogList (blogTitle, blogText) VALUES ('$_POST[blogTitle]','$_POST[blogText]')";
		//echo htmlentities($sql, ENT_QUOTES);
		//window.location.reload(true);
		return $dbh->exec($sql);
}
// Get list of blogs
function getBlogs($dbh) {
    $sql = "SELECT * FROM blogList";
    $blogs = $dbh->query($sql)->fetchAll();
    return $blogs;
}

$blogs = getBlogs($dbh);
$error = '' ;
$success = '' ;
$blog = isset($_POST['blogTitle' ]) ? $_POST['blogTitle' ] : '' ;
if ($_SERVER['REQUEST_METHOD' ] == 'POST' ) {
    if (blogExists($dbh, $blogTitle)) {
        $error = "Blog Title already exists on our list.";
    } elseif (insertBlog($dbh, $blogTitle, $blogText)) {
        $success = "Thank you, blog has been added.";
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
	<title>Blog List</title>
</head>

<body>
    <h2>Current Blogs</h2>
    <div>
        <?php 
            foreach($blogs as $blog) {
                echo htmlentities($blog['blogTitle'], ENT_QUOTES);
								echo "  ";
								echo htmlentities($blog['blogText'], ENT_QUOTES); 
                echo '<br/>';
            }
        ?>
    </div>
    <hr>

    <h2>Add to our BLOG list</h2>
    <div style="color: red">
       <?php echo htmlentities($error, ENT_QUOTES) ?>
    </div>
    <div style="color: green">
       <?php echo htmlentities($success, ENT_QUOTES) ?>
    </div>

    <form method="post" action="/booger.php">
      Blog Title <br/>
			<input type="text" name="blogTitle" size="25" />
		  <br/>Blog Text <br/>
			<input type="text" name="blogText" size="150" />
      <input type="submit" />
			<input type="reset" name="reset" id="reset"/>
    </form>
</body>
</html>


